import React, { Component } from 'react';
import PropTypes from 'prop-types';
// 内层 -- 展示组件 -- 傻瓜组件 -- 只负责接收 props 渲染，无 state
function Summary(props) {
  const { sum } = props;
  return (
    <div>Total Count: {sum}</div>
  )
}

// class Summary extends Component {
//   render() {
//     return (
//       <div>Total Count: {this.props.sum}</div>
//     )
//   }
// }

Summary.propTypes = {
  sum: PropTypes.number.isRequired
}

// 外层 -- 容器组件 -- 聪明组件
class SummaryContainer extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = this.getOwnState();
    this.onChange = this.onChange.bind(this);
    this.getOwnState = this.getOwnState.bind(this)
  }
  getOwnState() {
    const state = this.context.store.getState();
    let sum = 0;
    for (const key in state) {
      if (state.hasOwnProperty(key)) {
        sum += state[key];
      }
    }
    return {
      sum
    }
  }
  shouldComponentUpdate(nextProps, nextState) {
    return nextState.sum !== this.state.sum;
  }

  componentDidMount() {
    this.context.store.subscribe(this.onChange);
  }

  componentWillUnmount() {
    this.context.store.unsubscribe(this.onChange);
  }
  onChange() {
    this.setState(this.getOwnState());
  }
  render() {
    return (
      <Summary sum={this.state.sum} />
    )
  }
}
SummaryContainer.contextTypes = {
  store: PropTypes.object
}
export default SummaryContainer;